<template>
  <div class="app-container">
    <el-form ref="form" :rules="rules" :model="addListForm" label-width="100px">
      <el-col :span="8">
        <el-form-item prop="strUsername" label="节目单名称">
          <el-input
            v-model="addListForm.strUsername"
            placeholder="请输入节目单名称"
            style="max-width: 220px"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="iOrgsysnum" label="所属机构"> <!--prop 之前是strUsername-->
          <el-cascader
            v-model="addListForm.iOrgsysnum"
            style="width: 220px"
            :show-all-levels="false"
            :options="options"
            :props="{ checkStrictly: true, expandTrigger: 'hover', value:'strOrgnum',label:'strOrgname',children: 'yhlist'}"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="iUrgent" label="节目单类型">
          <el-select v-model="addListForm.iUrgent" placeholder="请选择">
            <el-option label="紧急" value="1"/>
            <el-option label="普通" value="0"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="strStartdate" label="生效日期">
          <el-date-picker
            v-model="addListForm.strStartdate"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="请选择生效日期"
            :picker-options="pickerOptions"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="strEnddate" label="截至效期">
          <el-date-picker
            v-model="addListForm.strEnddate"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="请选择有效期"
            :picker-options="pickerOptionss"
          />
        </el-form-item>
      </el-col>
      <el-col v-if="addListForm.iUrgent==='1'" :span="8">
        <el-form-item prop="iDevicesysnumArr" label="设备列表">
          <el-cascader
            v-model="addListForm.iDevicesysnumArr"
            :show-all-levels="false"
            :options="optionss"
            :props="{ multiple: true, checkStrictly: true,expandTrigger: 'hover', value:'iDevicesysnum',label:'strDevicename'}"
            @change="devicechange"
            @focus="devicefocus"
          />
        </el-form-item>
      </el-col>
      <!--<el-col :span="8">
        <el-form-item prop="iFrequency" label="播放次数">
          <el-select v-model="addListForm.iFrequency" placeholder="请选择播放次数">
            <el-option label="一次" value="1"></el-option>
            <el-option label="二次" value="2"></el-option>
            <el-option label="循环" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-col>-->
      <el-col :span="24">
        <el-form-item prop="strCycle" label="播放周期">
          <el-checkbox-group v-model="addListForm.strCycle">
            <el-checkbox v-for="(item, index) in playPeriod" :key="index" :label="item">
              {{ item }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="周期时间段">
          上午:
          <el-time-select
            v-model="addListForm.strCycleStartdata"
            placeholder="起始时间"
            :picker-options="{
              start: '00:00',
              step: '00:30',
              end: '12:00'
            }"
          />
          <el-time-select
            v-model="addListForm.strCycleEnddata"
            placeholder="结束时间"
            :picker-options="{
              start: '00:00',
              step: '00:30',
              end: '12:00',
              minTime: addListForm.strCycleStartdata
            }"
          />
          下午:
          <el-time-select
            v-model="addListForm.strCycleStarttime"
            placeholder="起始时间"
            :picker-options="{
              start: '12:00',
              step: '00:30',
              end: '24:00'
            }"
          />
          <el-time-select
            v-model="addListForm.strCycleEndtime"
            placeholder="结束时间"
            :picker-options="{
              start: '12:00',
              step: '00:30',
              end: '24:00',
              minTime: addListForm.strCycleStarttime
            }"
          />
        </el-form-item>
      </el-col>
      <!--设备列表展示-->
      <el-col :span="24">
        <el-form-item label="所选设备列表">
          <el-table :data="DeviceData" height="190" border>
            <el-table-column type="index" width="55" label="序号" align="center"/>
            <el-table-column prop="strDevicename" label="设备名称" align="center"/>
            <el-table-column prop="iDevicetype" label="设备类型" align="center"/>
            <el-table-column prop="appname" label="基础应用" align="center"/>
            <el-table-column label="创建者" align="center">
              <template>admin</template>
            </el-table-column>
            <el-table-column prop="strCreatetime" label="创建时间" align="center"/>
          </el-table>
        </el-form-item>
      </el-col>
    </el-form>
    <div class="filter-container">
      <h3 style="color:#fff">素材选择</h3>
      <div class="filter-container">
        <el-button type="primary" @click="addMaterial()">添加素材</el-button>
      </div>
      <el-table
        ref="multipleTable"
        :data="materialData"
        row-key="id"
        style="width: 100%"
        border
        :default-sort="{prop: 'time', order: 'ascending'}"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <!--<el-table-column type="index" width="55" label="序号" align="center"/>-->
        <el-table-column prop="strMaterialname" label="标题" align="center"/>
        <el-table-column prop="typeName" label="类型" align="center"/>
        <el-table-column prop="strOrgname" label="所属机构" align="center"/>
        <el-table-column prop="strDownload" label="下载地址" align="center"/>
        <el-table-column prop="time" sortable label="排序" width="80" align="center">
          <template slot-scope="{row}">
            <el-input v-model="row.iOrder"/>
          </template>
        </el-table-column>
        <el-table-column prop="time" label="播放次数" width="80" align="center">
          <template slot-scope="{row}">
            <el-input v-model="row.iPlaytime"/>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          align="center"
          label="操作"
          width="240"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click.native.prevent="deleteRow(scope.$index, materialData)"
            >
              移除
            </el-button>
            <!--<el-button size="mini" type="primary" @click="replaceMaterial(scope.row,scope.$index)">替换</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <span v-if="showspan" class="showspan">请勾选后提交</span>
    </div>
    <el-button type="primary" style="position: absolute;right: 21px;" @click="changeProgrammer('form')">保存</el-button>

    <el-dialog title="新增素材" :visible.sync="dialogVisible">
      <div class="container">
        <el-form :model="addForm" label-width="80px">
          <el-col :span="8">
            <el-form-item label="所属机构" label-width="80px" required="true">
              <el-cascader
                v-model="addForm.iOrgsysnum"
                :show-all-levels="false"
                :options="options"
                :props="{ expandTrigger: 'hover', checkStrictly: true, value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="strMaterialdetail" label="素材标签">
              <el-select v-model="addForm.strMaterialdetail" placeholder="请选择素材标签">
                <el-option
                  v-for="item in optionTag"
                  :key="item.id"
                  :label="item.strValue"
                  :value="item.strCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2" class="searbtn">
            <el-form-item>
              <el-button type="primary" @click="addsearch()">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-form>
        <el-table
          :data="addTableData"
          style="width: 100%"
          height="380"
          border
          @selection-change="changeFun"
        >
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column type="index" width="55" label="序号" align="center"/>
          <el-table-column prop="strMaterialname" label="标题" align="center"/>
          <el-table-column prop="typeName" label="格式" align="center"/>
          <el-table-column prop="strMaterialdetailName" label="标签" align="center"/>
          <el-table-column prop="strCreatetime" label="创建时间" align="center"/>
          <el-table-column label="预览" align="center">
            <template slot-scope="scope">
              <a :href="'http://'+scope.row.strDownload" target="_blank">{{ scope.row.strDownload }}</a>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addsearchture(),dialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getOrglist,
    getSysType,
    addsearchPrograms,
    changePrograms,
    getDevice
  } from '../../api/addTag'
  import Sortable from 'sortablejs'

  export default {
    name: 'AddProgramme',
    data() {
      return {
        // < 是选择今天及之后的时间，后面的-8.64e7就是可以选择今天和今天之后的。-8.64e6今天不可选
        // > 是选择今天以及今天之前的时间，后面的-8.64e6就是可以选择今天和今天之前的。
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        pickerOptionss: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        // 校验
        rules: {
          strUsername: [
            { required: true, message: '请输入应用名称', trigger: 'blur' },
            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
          ],
          iOrgsysnum: [
            { required: true, message: '请选择活动区域', trigger: 'change' }
          ],
          iUrgent: [
            { required: true, message: '请选择活动区域', trigger: 'change' }
          ],
          strStartdate: [
            { required: true, message: '请选择日期', trigger: 'change' }
          ],
          strEnddate: [
            { required: true, message: '请选择时间', trigger: 'change' }
          ],
          iFrequency: [
            { required: true, message: '请选择播放次数', trigger: 'change' }
          ],
          strCycle: [
            { type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }
          ],
          iDevicesysnumArr: [
            { type: 'array', required: true, message: '请选择列表', trigger: 'change' }
          ]
        },
        showspan: false,
        playPeriod: [
          '星期日',
          '星期一',
          '星期二',
          '星期三',
          '星期四',
          '星期五',
          '星期六'
        ],
        // checkPeriod: [],
        dialogVisible: false,
        optionTag: [],
        materialData: [],
        DeviceData: [],
        multipleSelection: [],
        sortable: null,
        addForm: {
          iOrgsysnum: '',
          strMaterialdetail: '',
          iFlag: 1
        },
        options: [],
        optionss: [],
        strCycle: [],
        addTableData: [],
        addListForm: {
          id: '',
          iProgramsysnum: '',
          iFrequency: '',
          strUsername: '',
          iUrgent: '',
          strStartdate: '',
          strEnddate: '',
          strCycle: [],
          strOperator: 'admin',
          // valArr: [],
          deviceType: 1,
          iPlaytime: '',
          iOrder: '',
          materialList: [],
          iOrgsysnum: [],
          // iOrgsysnum: '',
          strCycleStartdata: '', // 中午开始时间
          strCycleEnddata: '', // 中午结束时间
          strCycleStarttime: '', // 下午开始时间
          strCycleEndtime: '', // 下午结束时间
          iDevicesysnumArr: []

        }

      }
    },
    created() {
      this.fetchOrgList()
      // this.materialDataList()
      // 修改页面接收数据
      this.addListForm.strUsername = this.$route.query.rowAll.strUsername
      this.addListForm.iOrgsysnum = this.$route.query.rowAll.iOrgsysnum.toString()
      this.strDevicename = this.$route.query.rowAll.strDevicename
      this.addListForm.iUrgent = this.$route.query.rowAll.iUrgent.toString()
      this.addListForm.strStartdate = this.$route.query.rowAll.strStartdate
      this.addListForm.strEnddate = this.$route.query.rowAll.strEnddate
      this.addListForm.strCycleStarttime = this.$route.query.rowAll.strCycleStarttime
      this.addListForm.strCycleEndtime = this.$route.query.rowAll.strCycleEndtime
      this.addListForm.iFrequency = this.$route.query.rowAll.iFrequency.toString()
      if (this.$route.query.rowAll.strCycle) {
        this.addListForm.strCycle = this.$route.query.rowAll.strCycle.split(',') // 将传过来的字符串用逗号隔开转化为数组(星期)
      }
      this.addListForm.strCycleStartdata = this.$route.query.rowAll.strCycleStartdata
      this.addListForm.strCycleEnddata = this.$route.query.rowAll.strCycleEnddata
      // console.log(this.$route.query.rowAll.strCycle.split(","))
      // this.addListForm.strCycle = this.$route.query.rowAll.strCycle
      // console.log(this.$route.query.rowAll)
      this.addListForm.iProgramsysnum = this.$route.query.rowAll.iProgramsysnum
      this.addListForm.id = this.$route.query.rowAll.id
      // this.addListForm.iPlaytime = this.$route.query.rowAll.iPlaytime
      this.materialData = this.$route.query.dataAll
      this.deviceShow() //
    },
    mounted() {
      this.rowDrop()
    },
    methods: {
      // 设备列表input框focus触发
      devicefocus() {
        if (this.addListForm.iOrgsysnum.length > 0) {
          this.getAllDeviceList()
        } else {
          this.$message({
            message: '请先选择机构',
            type: 'warning'
          })
        }
      },

      // 修改页面加载时根据传过来的所属机构编号获取设备列表表格数据
      deviceShow() {
        this.getDeviceListShow()
      },
      // 根据所属机构显示紧急时设备列表
      /* changecheck(val) {
          if (this.addListForm.iOrgsysnum instanceof Array) {
            this.addListForm.iOrgsysnum = this.addListForm.iOrgsysnum.splice(-1).toString()
            console.log(this.addListForm.iOrgsysnum)
          }
          console.log(val)
          this.getAllDeviceList()
        },*/

      // 根据设备列表input focus 触发展示的设备列表数据
      getAllDeviceList() {
        const ids = []
        this.addListForm.iDevicesysnumArr.map(item => {
          ids.push(item.iDevicesysnum)
        })
        // this.iDevicesysnumArr = ids
        getDevice({ iOrgsysnum: this.addListForm.iOrgsysnum, iDevicesysnumArr: ids }).then(res => {
          this.optionss = res.deviceList
        })
      },

      // 点击设备列表多选框的时候触发事件
      devicechange(val) {
        this.iDevicesysnumArr = val
      },

      // 点击列表页面修改按钮加载进来时 展示的设备列表数据
      getDeviceListShow() {
        const ids = []
        this.addListForm.iDevicesysnumArr.map(item => {
          ids.push(item.iDevicesysnum)
        })
        // this.iDevicesysnumArr = ids
        getDevice({
          iOrgsysnum: this.addListForm.iOrgsysnum,
          iProgramsysnum: this.addListForm.iProgramsysnum,
          iDevicesysnumArr: ids
        }).then(res => {
          this.DeviceData = res.retList
        })
        // 素材所列表格被选中
        this.materialData.forEach((i, index) => {
          this.$nextTick(() => {
            this.$refs.multipleTable.toggleRowSelection(i, true)
          })
        })
      },
      // 去除相同数据方法
      /* uniqueArr(materialData, addTableData) {
          let arr = addTableData.filter(item => {
            let str = JSON.stringify(item)
            return materialData.every(item => JSON.stringify(item) != str)
          })
          this.addTableData = arr
        },*/
      // this.uniqueArr(materialData,addTableData)
      // 获取节目单列表
      fetchOrgList() {
        // 获取机构数据
        getOrglist().then(res => {
          this.options = res.data
        })
        // 获取素材标签列表
        getSysType({ typeInfo: [3, 4, 7] }).then(res => {
          this.optionType = res.data[4]
          this.optionTag = res.data[3]
          this.iDevTypes = res.data[7]
        })
      },

      // 添加节目单中添加素材按钮
      addMaterial(row, index) {
        this.dialogVisible = true

        /* this.materialData = this.multipleSelection
          this.addTableData = this.addTableData*/
        this.uniqueArr(this.materialData, this.addTableData)
      },

      handleSelectionChange(val) {
        this.addListForm.materialList = val
        // this.addListForm.valArr = val
        /* let list = JSON.stringify(val)
          this.addListForm.materialList = list
          val.forEach((val, index) => {
            this.materialData.forEach((v, i) => {
              // id 是每一行的数据id
              if (val.id == v.id) {
                //console.log(i)
              }
              let yi = i
              console.log(yi)
            })
          })*/
      },

      // 修改节目单
      changeProgrammer(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const arr = []
            this.strCycle.map(item => {
              item.map(value => {
                arr.push(value)
              })
            })
            this.addProgramswar([...new Set(arr)])
            // alert('submit!')
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },

      addProgramswar(arr,sDate1,sDate2) {
        if (this.addListForm.iOrgsysnum instanceof Array) {
          this.addListForm.iOrgsysnum = this.addListForm.iOrgsysnum.splice(-1).toString()
        }

        // 判断所选日期是否与所选星期是否匹配
        const weeks = this.addListForm.strCycle
        let timestr1 = this.addListForm.strStartdate
        let timestr2 = this.addListForm.strEnddate

        let getWeek_index1 = (new Date(timestr1)).getDay()
        let getWeek_index2 = (new Date(timestr2)).getDay()
        const weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']

        let dateSpan, iDays
        sDate1 = Date.parse(timestr1)
        sDate2 = Date.parse(timestr2)
        dateSpan = sDate2 - sDate1
        dateSpan = Math.abs(dateSpan)
        iDays = Math.floor(dateSpan / (24 * 3600 * 1000)) + 1

        let judgeValue = false
        if (iDays < 7) {
          let selectList = weekArr.slice(getWeek_index1, getWeek_index2 + 1)
          weeks.map((item, index) => {
            // indexOf检索字符串值有没有出现
            if (selectList.indexOf(item) == -1) {
              judgeValue = true
              return
            }
          })
        }
        if (judgeValue) {
          this.$message({
            message: '请选择' + weekArr[getWeek_index1] + '到' + weekArr[getWeek_index2],
            type: 'warning'
          })
          return
        }

        // 判断节目单素材管理表格提交没有数据的时候直接提交，有数据的时候提示选择后提交
        if (this.materialData.length > 0) {
          let isFlase = false
          const showarr = []
          this.materialData.forEach((item, index) => {
            showarr.push(item.iOrder)
            const s = showarr.join(',')
            if (item.iPlaytime === '' || item.iOrder === '' || s.replace(showarr[index], '').indexOf(showarr[index]) > -1) {
              isFlase = true
            } else {
              isFlase = false
            }
          })
          if (isFlase === false) {
            this.addListForm.materialList = JSON.stringify(this.addListForm.materialList)
            changePrograms(this.addListForm).then(res => {
              this.addListForm.strCycle = arr
              this.$router.push({ path: '/programme/index' })
            })
          } else {
            this.$message({
              message: '排序或播放次数不能为空或排序不可相同',
              type: 'warning'
            })
          }
        } else {
          this.addListForm.materialList = JSON.stringify(this.addListForm.materialList)
          changePrograms(this.addListForm).then(res => {
            this.addListForm.strCycle = arr
            // this.addListForm.materialList = this.materialData
            // console.log(res)
            this.$router.push({ path: '/programme/index' })
          })
        }
      },

      // 新增页面弹窗中搜索
      addsearch(param) {
        if (this.addForm.iOrgsysnum instanceof Array) {
          this.addForm.iOrgsysnum = this.addForm.iOrgsysnum.splice(-1).toString()
        }

        addsearchPrograms(this.addForm).then(res => {
          // this.uniqueArr(this.materialData, this.addTableData)
          this.addTableData = res.result
          this.uniqueArr(this.materialData, this.addTableData)

          // console.log(this.addTableData)
        })
      },

      // 点击新增素材弹窗中复选框
      changeFun(val) {
        this.multipleSelection = val
        // console.log(val)
      },

      // 点击新增素材弹窗确认按钮
      addsearchture() {
        this.materialData = this.materialData.concat(this.multipleSelection)
        // console.log(this.materialData)
        this.materialData.forEach((i, index) => {
          this.$nextTick(() => {
            this.$refs.multipleTable.toggleRowSelection(i, true)
          })
        })
      },

      // 移除当前行数据
      deleteRow(index, rows) {
        rows.splice(index, 1)
        this.uniqueArr(this.materialData, this.addTableData)
      },

      // 行拖拽
      rowDrop() {
        const tbody = document.querySelector('.el-table__body-wrapper tbody')
        const _this = this
        Sortable.create(tbody, {
          onEnd({ newIndex, oldIndex }) {
            const currRow = _this.materialData.splice(oldIndex, 1)[0]
            _this.materialData.splice(newIndex, 0, currRow)
          }
        })
      }
      /* changeProgrammer() {
          changePrograms(this.addListForm).then({

          })
          this.$router.push({ path: '/programme/index' })
        }*/
    }
  }
</script>
<style type="scss" scoped>
  .searbtn {
    margin-left: -60px;
  }

  .showspan {
    color: red;
    font-size: 12px;
  }
</style>
